/*
 * Created on May 22, 2004
 *
 * Vectrics Inc.  GNU Public License.
 */
package org.vectrics.recruiter.struts.admin;

import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.vectrics.SystemException;
import org.vectrics.common.util.StringUtils;
import org.vectrics.company.Company;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.location.Location;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.job.JobFunction;
import org.vectrics.recruiter.job.JobSearchCriteria;
import org.vectrics.recruiter.struts.JobSearchForm;
import org.vectrics.recruiter.struts.tag.JobDetailDisplayOptions;
import org.vectrics.struts.Request;
import org.vectrics.user.Person;

/**
 * @author mmoore
 */
public class JobSearchActionHelper {
	
	private transient static Log log = LogFactory.getLog(JobSearchActionHelper.class);
	public static String JOB_CRITERIA_ATTRIBUTE_NAME = "job.criteria";
	public static String JOB_DISPLAY_ATTRIBUTE_NAME = "job.display";
	public static String TIME_PARAM = "time";
	
	/**
	 * 
	 */
	public JobSearchActionHelper() {
		super();
	}
	
	public void storeDisplayOptions(Request request, 
			JobDetailDisplayOptions options) {
		request.setSessionAttribute(JOB_DISPLAY_ATTRIBUTE_NAME, options);
	}
	
	public JobDetailDisplayOptions loadDisplayOptions(Request request) {
		JobDetailDisplayOptions options 
			= (JobDetailDisplayOptions)request.getSessionAttribute(JOB_DISPLAY_ATTRIBUTE_NAME);
		if (options == null)
		    throw new SystemException("Could not find required request attribute: "
		    		+ JOB_DISPLAY_ATTRIBUTE_NAME);
		return(options);
	}
	
	public void storeCriteria(Request request, JobSearchCriteria criteria) {
		request.setSessionAttribute(JOB_CRITERIA_ATTRIBUTE_NAME, criteria);
	}
	
	public JobSearchCriteria loadCriteria(Request request) {
		JobSearchCriteria criteria = (JobSearchCriteria)request.getSessionAttribute(JOB_CRITERIA_ATTRIBUTE_NAME);
		return(criteria);
	}
	
	public JobDetailDisplayOptions formToDisplayOptions(JobSearchForm jobSearchForm) {
		if (log.isDebugEnabled()) {
			log.debug("execute() - form.showBlock           = " + jobSearchForm.getShowBlock());
			log.debug("execute() - form.showActiveIndicator = " + jobSearchForm.getShowActiveStatus());
			log.debug("execute() - form.alternateRows       = " + jobSearchForm.getAlternateRowColors());
			log.debug("execute() - form.showDescription     = " + jobSearchForm.getShowDescription());
		}
		
		JobDetailDisplayOptions options = new JobDetailDisplayOptions();

		if ((jobSearchForm.getShowBlock() != null) && (jobSearchForm.getShowBlock().startsWith("tr"))) {
			options.setRowStyle(JobDetailDisplayOptions.STYLE_BLOCK);
		} else {
			options.setRowStyle(JobDetailDisplayOptions.STYLE_RECORD_PER_LINE);
		}

		if (jobSearchForm.getShowActiveStatus() != null) {
			if (jobSearchForm.getShowActiveStatus().startsWith("tr")) {
				options.setShowActiveIndicator(true);
			}
		} else {
			if ((jobSearchForm.getActiveStatus() == null) || (jobSearchForm.getActiveStatus().startsWith("all")))
				options.setShowActiveIndicator(true);
		}
		
		if (jobSearchForm.getShowPdfLink() != null) {
			if (jobSearchForm.getShowPdfLink().startsWith("tr")) {
				options.setShowPdfLink(true);
			}
		} else {
			options.setShowPdfLink(false);
		}
		
		options.setAlternateRowColors(false);
		if (jobSearchForm.getAlternateRowColors() != null) {
			if (jobSearchForm.getAlternateRowColors().startsWith("tr")) {
				options.setAlternateRowColors(true);
			}
		}
		
		options.setShowDescription(false);
		if (jobSearchForm.getShowDescription() != null) {
			if (jobSearchForm.getShowDescription().startsWith("tr")) {
				options.setShowDescription(true);
			}
		} else if (options.getRowStyle() == JobDetailDisplayOptions.STYLE_BLOCK) {
			options.setShowDescription(true);
		}
		
		options.setShowRecruiter(false);
		if (jobSearchForm.getShowRecruiter() != null) {
			if (jobSearchForm.getShowRecruiter().startsWith("tr")) {
				options.setShowRecruiter(true);
			}
		} else if (options.getRowStyle() == JobDetailDisplayOptions.STYLE_BLOCK) {
			options.setShowRecruiter(true);
		}
		
		options.setShowCompany(false);
		if (jobSearchForm.getShowCompany() != null) {
			if (jobSearchForm.getShowCompany().startsWith("tr")) {
				options.setShowCompany(true);
			}
		} else if (options.getRowStyle() == JobDetailDisplayOptions.STYLE_BLOCK) {
			options.setShowCompany(true);
		}
		
		options.setShowCompanyCode(false);
		if (jobSearchForm.getShowCompanyCode() != null) {
			if (jobSearchForm.getShowCompanyCode().startsWith("tr")) {
				options.setShowCompanyCode(true);
			}
		}
		
		options.setShowReferenceCode(false);
		if (jobSearchForm.getShowReferenceCode() == null) {
			if (options.getRowStyle() == JobDetailDisplayOptions.STYLE_BLOCK) {
				options.setShowReferenceCode(true);
			}
		} else {
			options.setShowReferenceCode(jobSearchForm.getShowReferenceCode().startsWith("tr"));
		}
		
		if (jobSearchForm.getShowLocation() == null) {
			if (options.getRowStyle() == JobDetailDisplayOptions.STYLE_BLOCK) {
				options.setShowLocation(true);
			} else {
				options.setShowLocation(true);			}
		} else {
			options.setShowLocation(jobSearchForm.getShowLocation().startsWith("tr"));
		}
		
		if (log.isDebugEnabled()) {
			log.debug("execute() - options.rowStyle        = " + options.getRowStyle());
		}
		
		return(options);
	}
	
	public JobSearchCriteria formToCriteria(JobSearchForm jobSearchForm, Request request) {
		Person authPerson = ThreadProperties.getPerson();
		String companyIdParam = jobSearchForm.getCompanyId();
		String functionId = jobSearchForm.getFunctionCode();
//		String searchWords = jobSearchForm.getSearchPhrase();
		String searchWords = null;
		String locationId = jobSearchForm.getLocation();
		String referenceId = jobSearchForm.getReferenceId();
		String postedTimeParam = jobSearchForm.getPostedStartTime();
		String createdTimeParam = jobSearchForm.getCreatedStartTime();
		String activeStatus = jobSearchForm.getActiveStatus();
		String needApproval = jobSearchForm.getNeedApproval();
		String title = jobSearchForm.getTitle();
		String primaryRecruiter = jobSearchForm.getPrimaryRecruiter();
		String requester = jobSearchForm.getRequester();
		
		Long companyId = null;
		if (companyIdParam != null)
		    companyId = new Long(companyIdParam);
		
		if (log.isDebugEnabled()) {
			log.debug("execute() - function id = " + functionId);
//			log.debug("execute() - searchWords = " + searchWords);
			log.debug("execute() - locationId =  " + locationId);
			log.debug("execute() - timeParam =   " + postedTimeParam);
		}
		
		JobSearchCriteria criteria = new JobSearchCriteria();
		if ((StringUtils.isNullOrBlank(postedTimeParam)) || (postedTimeParam.equals("-1"))) {
			criteria.setEarliestPostDate(null);
		} else {
			try {
				if(postedTimeParam.equals("0")) {
					log.debug("Start time not given");
					criteria.setEarliestPostDate(null);
				} else {
					Date now = new Date();
					long startTime = now.getTime() - (Long.parseLong(postedTimeParam) * 1000 * 60 * 60);
					criteria.setEarliestPostDate(new Date(startTime));
				}
			}
			catch (Exception ex) {
				log.error("doRender() - illegal value for param: " + TIME_PARAM + "  value = " + postedTimeParam);
			}
		}

		if (StringUtils.isNullOrBlank(referenceId) == false) {
			criteria.addReferenceCode("%" + referenceId + "%");
		}

		if (StringUtils.isNullOrBlank(needApproval) == false) {
			criteria.setJobsNeedingApproval(true);
		}
		
		
		if (StringUtils.isNullOrBlank(createdTimeParam) == false) {
			try {
				if(createdTimeParam.equals("0")) {
					log.debug("Start time not given");
					criteria.setEarliestCreateDate(null);
				} else {
					Date now = new Date();
					long startCreateTime = now.getTime() - (Long.parseLong(createdTimeParam) * 1000 * 60 * 60);
					criteria.setEarliestCreateDate(new Date(startCreateTime));
				}
			}
			catch (Exception ex) {
				log.error("doRender() - illegal value for param: " + TIME_PARAM + "  value = " + createdTimeParam);
			}
		} else {
			criteria.setEarliestCreateDate(null);
		}
		
		if ((activeStatus != null) && (!activeStatus.trim().equals(""))) { 
			criteria.addStatusTypeCode(activeStatus);
		} else {
			if (activeStatus != null) {
				criteria.getStatusTypes().clear();
			}
		}
	
		if (searchWords == null)
			criteria.setSearchWords(searchWords);
		else
			criteria.setSearchWords(searchWords.toLowerCase());
		
		if ((functionId != null) && (functionId.trim().length() > 0)) {
			JobFunction function = RecruitServiceLocator.getJobProvider().findFunction(functionId);
			Collection jobFunctions = new HashSet();
			jobFunctions.add(function);
			criteria.setJobFunctions(jobFunctions);
		}
		
		if ((locationId != null) && (locationId.trim().length() > 0)) {
			Location location = CoreServiceLocator.getLocationService().findLocation(new Long(locationId));
			Collection locations = new HashSet();
			locations.add(location);
			criteria.setLocations(locations);
		}
		
		if (companyId != null) {
			Company company = CoreServiceLocator.getCompanyService().findCompany(companyId);
			criteria.addCompany(company);
			criteria.addDomain(company.getDomain());
		}
		
		
		if (request != null) {
			Iterator<String> paramNames = request.getParameterNames().iterator();
			while (paramNames.hasNext()) {
				String paramName = (String)paramNames.next();
				if (paramName.startsWith("company_")) {
					Long compId = new Long(paramName.substring(8));
					Company company = CoreServiceLocator.getCompanyService().findCompany(compId);
					criteria.addCompany(company);
					criteria.addDomain(company.getDomain());
				}
			}
		}

		if (authPerson == null) {
			criteria.addDomain(ThreadProperties.getDomain());
		} else {
			if (criteria.getDomains().size() == 0) {
				Set domains = authPerson.findDomainsForPrivilege("job.view");
				criteria.setDomains(domains);
			}
		}
			
		if (title!=null){
			criteria.setTitle("%"+title);
		}
		
		if ((primaryRecruiter != null) && (!primaryRecruiter.trim().equals(""))){
			criteria.setPrimaryRecruiter(new Long(primaryRecruiter));
		}
		
		if ((requester != null) && (!requester.trim().equals(""))) {
			criteria.setRequester(new Long(requester));
		}
		
		return(criteria);
	}
	
}
